package com.hotel.BL;

import java.util.Date;

import com.EntityName;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.SortDirection;

import data.CounterPayment;

public class CounterPaymentLogic extends AbstractBL {
	public CounterPayment AddCounterPayment(long hotelId,String counterString,
			double openAmount,Date openDate,Date openNightAuditDate,double totalAmount) throws EntityNotFoundException{
		CounterPayment t = new CounterPayment();
		t.setCounterString(counterString);
		t.setHotelId(hotelId);
		t.setOpenAmount(openAmount);
		t.setOpenDate(openDate);
		t.setOpenNightAuditDate(openNightAuditDate);
		t.setTotalAmount(totalAmount);
		Key k = datastore.put(t.getEntity());
		t.setId(k.getId());
		t.setKey(k);

		return t;
	}
	
	public CounterPayment GetLastCounterPayment(long hotelId,String counter){
			Query q = new Query(EntityName.CounterPayment);
			
			Filter filterHotel = new FilterPredicate("hotelId",FilterOperator.EQUAL,hotelId);
			Filter filterTitle = new FilterPredicate("counter",FilterOperator.EQUAL,counter);

			Filter filter = CompositeFilterOperator.and(filterHotel,filterTitle);
			
			q.setFilter(filter).addSort("closeDate", SortDirection.ASCENDING);
			
			int countEntities = datastore.prepare(q).countEntities(FetchOptions.Builder.withDefaults());
			
			if(countEntities != 0){
				return GetCounterPayment(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()).get(0));
			}else{
				return null;
			}		
	}
	
	public CounterPayment GetCounterPayment(Entity entity)
	{
		if(entity == null) return null;
		CounterPayment item = new CounterPayment();
		item.setEntity(entity);
		return item;
	}
	
	public CounterPayment GetCounterPayment(long l)
	{
		Key key = KeyFactory.createKey(EntityName.CounterPayment, l);
		try {
			Entity lang = datastore.get(key);
			CounterPayment c = new CounterPayment();
			c.setEntity(lang);
			return c;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
}
